import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  getClearApplyList,
  createClearApply,
  updateClearApply,
  deleteClearApply
} from "@/api/ads";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import { useRoute } from "vue-router";
import type { 
  AdClearApplyFormItemProps, 
  AdClearApplyTableItemProps, 
  AdClearApplyHandleFormItemProps,
  SelectOption,
  AD_CLEAR_APPLY_STATE
} from "./types";
import { deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { applyFormRules, handleFormRules } from "./rule";

export function useAdClearApply() {
  const route = useRoute();
  
  const form = reactive({
    account_id: "",
    state: "",
    creator_id: "",
    created_at: [],
    feedback_at: []
  });

  const formRef = ref();
  const handleFormRef = ref();
  const dataList = ref<AdClearApplyTableItemProps[]>([]);
  const loading = ref(true);
  const stateOptions = ref<SelectOption[]>([]);
  const accountOptions = ref<SelectOption[]>([]);
  const creatorOptions = ref<SelectOption[]>([]);
  
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100],
    currentPage: 1,
    background: true
  });

  // 格式化时间
  const formatTime = (timestamp: number) => {
    if (!timestamp) return "-";
    return new Date(timestamp * 1000).toLocaleString("zh-CN");
  };

  // 获取状态标签类型
  const getStateTagType = (state: number) => {
    switch (state) {
      case 1:
        return "warning";
      case 2:
        return "success";
      case 3:
        return "danger";
      default:
        return "info";
    }
  };

  // 获取状态文本
  const getStateText = (state: number) => {
    switch (state) {
      case 1:
        return "待处理";
      case 2:
        return "已清零";
      case 3:
        return "已驳回";
      default:
        return "未知";
    }
  };

  // 判断是否可以处理
  const canHandle = (state: number) => {
    return state === 1; // 只有待处理状态可以操作
  };

  // 判断是否可以删除
  const canDelete = (state: number) => {
    return state === 1; // 只有待处理状态可以删除
  };

  // 获取平台文本
  const getPlatformText = (platform: number | string | null | undefined): string => {
    if (!platform) return "未知平台";
    
    const platformNum = typeof platform === 'string' ? parseInt(platform) : platform;
    
    switch (platformNum) {
      case 1:
        return "TikTok";
      case 2:
        return "Facebook";
      default:
        return "未知平台";
    }
  };

  // 格式化平台和代理商信息
  const formatPlatformAgent = (adAccount: any): string => {
    if (!adAccount || !adAccount.ad_agent) return "-";
    
    const platform = getPlatformText(adAccount.ad_agent.platform);
    const agentName = adAccount.ad_agent.name || "-";
    
    return `${platform} | ${agentName}`;
  };

  const columns: TableColumnList = [
    {
      label: "申请ID",
      prop: "id",
      width: 80,
      align: "center"
    },
    {
      label: "平台代理商",
      prop: "ad_account",
      minWidth: 150,
      showOverflowTooltip: true,
      formatter: ({ ad_account }) => formatPlatformAgent(ad_account)
    },
    {
      label: "广告账号",
      prop: "ad_account",
      minWidth: 120,
      showOverflowTooltip: true,
      formatter: ({ ad_account }) => ad_account?.account_no || "-"
    },

    {
      label: "申请人",
      prop: "creator",
      width: 100,
      showOverflowTooltip: true,
      formatter: ({ creator }) => creator?.username || "-"
    },
    {
      label: "申请时间",
      prop: "created_at",
      width: 160,
      formatter: ({ created_at }) => formatTime(created_at || 0)
    },
    {
      label: "处理状态",
      prop: "state",
      width: 100,
      align: "center",
      cellRenderer: ({ row }) => (
        <el-tag
          type={getStateTagType(row.state)}
          effect="plain"
          size="small"
        >
          {getStateText(row.state)}
        </el-tag>
      )
    },
    {
      label: "处理时间",
      prop: "feedback_at",
      width: 160,
      formatter: ({ feedback_at }) => formatTime(feedback_at || 0)
    },
    {
      label: "反馈内容",
      prop: "feedback_content",
      minWidth: 150,
      showOverflowTooltip: true,
      formatter: ({ feedback_content }) => feedback_content || "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        ...form
      };

      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === "" || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });

      const { data } = await getClearApplyList(params);
      console.log("data", data);
      dataList.value = data.data || [];
      pagination.total = data.total || 0;

      // 更新选项数据
      if (data.state_options) {
        stateOptions.value = data.state_options;
      }
      if (data.account_options) {
        accountOptions.value = data.account_options;
      }
      if (data.creator_options) {
        creatorOptions.value = data.creator_options;
      }
    } catch (error) {
      console.error("获取清零申请列表失败:", error);
      message("获取清零申请列表失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  function openDialog(title = "新增", row?: AdClearApplyTableItemProps) {
    addDialog({
      title: `${title}清零申请`,
      props: {
        formInline: {
          account_id: row?.account_id ?? "",
        },
        accountOptions: accountOptions.value
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
              contentRenderer: () => h(editForm, { 
          ref: formRef,
          formInline: {
            account_id: row?.account_id ?? 0,
          },
          accountOptions: accountOptions.value
        }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as AdClearApplyFormItemProps;
        
        function chores() {
          message(`您${title}了账号为 ${curData.account_id} 的清零申请`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              createClearApply(curData).then(response => {
                if (response.code === 0) {
                  chores();
                } else {
                  // 业务错误，显示服务器返回的错误信息
                  message(response.message || "创建清零申请失败", { type: "error" });
                }
              }).catch(error => {
                console.error("创建清零申请失败:", error);
                // 网络或其他错误
                const errorMessage = error?.response?.data?.message || error?.message || "创建清零申请失败";
                message(errorMessage, { type: "error" });
              });
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              console.log("编辑功能暂未实现");
              message("编辑功能暂未实现", { type: "warning" });
            }
          }
        });
      }
    });
  }

  function openHandleDialog(row: AdClearApplyTableItemProps) {
    const processForm = reactive({
      state: 2,
      feedback_content: ""
    });

    const handleStateOptions = [
      { 
        value: 2, 
        label: "确认清零",
        tip: "确认已完成清零操作"
      },
      { 
        value: 3, 
        label: "驳回申请",
        tip: "驳回此次清零申请"
      }
    ];

    addDialog({
      title: "处理清零申请",
      props: {
        formInline: processForm
      },
      width: "500px",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <el-form
          ref={handleFormRef}
          model={processForm}
          rules={handleFormRules}
          label-width="100px"
        >
          <el-form-item label="平台代理商">
            <span style="font-weight: 500;">
              {formatPlatformAgent(row.ad_account)}
            </span>
          </el-form-item>
          
          <el-form-item label="广告账号">
            <span style="font-weight: 500;">
              {row.ad_account?.account_no || "未知账号"}
            </span>
          </el-form-item>

          <el-form-item label="申请人">
            <span style="font-weight: 500;">
              {row.creator?.username || "-"}
            </span>
          </el-form-item>

          <el-form-item label="申请时间">
            <span style="font-weight: 500;">
              {formatTime(row.created_at || 0)}
            </span>
          </el-form-item>
          
          <el-form-item label="处理状态" prop="state">
            <el-radio-group v-model={processForm.state}>
              {handleStateOptions.map(option => (
                <el-radio key={option.value} label={option.value}>
                  {option.label}
                  {option.tip && <span style="color: #999; font-size: 12px;">（{option.tip}）</span>}
                </el-radio>
              ))}
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="反馈内容" prop="feedback_content">
            <el-input
              v-model={processForm.feedback_content}
              type="textarea"
              rows={3}
              placeholder="请输入处理反馈内容（可选）"
              maxlength={255}
              show-word-limit
            />
          </el-form-item>
        </el-form>
      ),
      beforeSure: async (done) => {
        if (!handleFormRef.value) return;

        handleFormRef.value.validate(async (valid) => {
          if (valid) {
            try {
              await updateClearApply({id: row.id, ...processForm});
              const statusText = processForm.state === 2 ? "清零" : "驳回";
              message(`申请处理成功，状态已更新为：已${statusText}`, { type: "success" });
              done();
              onSearch();
            } catch (error) {
              console.error("处理清零申请失败:", error);
              const errorMessage = error?.response?.data?.message || error?.message || "处理失败";
              message(errorMessage, { type: "error" });
            }
          }
        });
      }
    });
  }

  async function handleDelete(row: AdClearApplyTableItemProps) {
    try {
      const response = await deleteClearApply({id: row.id});
      if (response.code === 0) {
        message(`删除成功`, { type: "success" });
        onSearch();
      } else {
        // 业务错误，显示服务器返回的错误信息
        message(response.message || "删除失败", { type: "error" });
      }
    } catch (error) {
      console.error("删除清零申请失败:", error);
      // 网络或其他错误
      const errorMessage = error?.response?.data?.message || error?.message || "删除失败";
      message(errorMessage, { type: "error" });
    }
  }

  onMounted(() => {
    // 检查路由参数，设置默认筛选条件
    const stateParam = route.query.state;
    if (stateParam && stateParam === "1") {
      form.state = 1; // 设置为待处理状态
    }
    
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    stateOptions,
    accountOptions,
    creatorOptions,
    onSearch,
    resetForm,
    openDialog,
    openHandleDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    canHandle,
    canDelete
  };
} 